import cn.hutool.core.util.CharsetUtil;
import cn.hutool.setting.Setting;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class HostAdress {
    private String hostAdress;
    private String inet4Address;
    private String inet6Address;

    public String getHostAdress() {
        return hostAdress;
    }

    public HostAdress setHostAdress(String hostAdress) {
        this.hostAdress = hostAdress;
        return this;
    }

    public String getInet4Address() {
        return inet4Address;
    }

    public HostAdress setInet4Address(String inet4Address) {
        this.inet4Address = inet4Address;
        return this;
    }

    public String getInet6Address() {
        return inet6Address;
    }

    public HostAdress setInet6Address(String inet6Address) {
        this.inet6Address = inet6Address;
        return this;
    }

    @Override
    public String toString() {
        return "HostAdress{" +
                "hostAdress='" + hostAdress + '\'' +
                ", inet4Address='" + inet4Address + '\'' +
                ", inet6Address='" + inet6Address + '\'' +
                '}';
    }

    public static void main(String[] args) {
        HostAdress host = getHost();
        System.out.println(host);
    }

    /**
     * 获取当前设备ipv4 ipv6等信息
     *
     * @return
     */
    public static HostAdress getHost() {
        HostAdress host = new HostAdress();
        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            host.setHostAdress(hostAddress);
            String hostName = InetAddress.getLocalHost().getHostName();
            if (hostName.length() > 0) {
                InetAddress[] addrs = InetAddress.getAllByName(hostName);
                if (addrs.length > 0) {
                    for (int i = 0; i < addrs.length; i++) {
                        InetAddress address = addrs[i];
                        if (address instanceof Inet6Address) {
//                            临时ipv6地址 亦可通过接口 http://ipv6.lookup.test-ipv6.com/ip/ 获取
                            if (addrs.length >= 2 && i == addrs.length - 2)
                                host.setInet6Address(address.getHostAddress());
                        } else if (address instanceof Inet4Address) {
                            host.setInet4Address(address.getHostAddress());
                        } else {
                            return null;
                        }
                    }
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
        return host;
    }

    /**
     * 获取配置文件值
     *
     * @param name 配置项名称 即key
     * @return
     */
    public static String getSet(Config name) {
        Setting setting = new Setting(Main.dirPath + "ddns.setting", CharsetUtil.CHARSET_UTF_8, false);
        return setting.getStr(name.toString(), "");
    }
}
